package com.caac.core.web.action.user;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.caac.core.dm.NormalUser;
import com.caac.core.dm.Role;
import com.caac.core.service.UserManager;
import com.caac.core.web.action.BaseAction;
import com.caac.core.web.form.BaseForm;
import com.caac.core.web.form.UserForm;

import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import java.util.Iterator;

public class AddUserAction extends BaseAction {

    protected ActionForward doExecute(ActionMapping mapping,
                                      BaseForm form,
                                      HttpServletRequest request,
                                      HttpServletResponse response) throws java.
            lang.Exception {
        UserForm uf = (UserForm) form;
        String id = request.getParameter("id");
        UserManager manager = this.getUserManager();
       
        uf.setRoles(manager.getAllRoles());
        if (id == null) {
            NormalUser user = new NormalUser();
            user.setState("1");
            uf.setUser(user);
            uf.setPassword(null);
            //uf.setRoleId(null);
            uf.setRoleIds(null);
        } else {
            NormalUser user = (NormalUser) manager.getUserById(id);
            uf.setUser(user);
            //uf.setRoleId(this.getRoleId(user.getRoles()));
            uf.setRoleIds(this.getRoleIds(user.getRoles()));
            uf.setPassword(user.getPassword());
         }
        request.setAttribute("id",id);
        return this.forward(mapping);
    }
/*
    private String getRoleId(Set roles) {
        if (roles.iterator().hasNext()) {
            Role role = (Role) roles.iterator().next();
            return role.getId();
        }
        return null;
    }
 */
    private String[] getRoleIds(Set roles) {
        int iNo=0;
        String[] roleIds = new String[roles.size()];
        for (Iterator it = roles.iterator(); it.hasNext(); ) {
            Role role = (Role) it.next();
            roleIds[iNo]= role.getId();
            iNo++;
        }
        return roleIds;
    }
}
